<template>
  <div class="applicationShop">
    <div class="mains_contain">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="uploadCon">上传</el-button>
      <div class="containList">
        <div class="containItem" v-for="(item, index) in containList" :key="index">
          <div class="containItem_top">
            <img src="../../assets/images/xhlogo.png" alt="" />
            <div class="right">
              <div>{{ item.name }}</div>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addTaskU(item)">任务</el-button>
              <!-- <el-button type="primary" size="mini" icon="el-icon-plus" v-if="item.task == 2" @click="deployment">部署</el-button> -->
            </div>
          </div>
          <div class="containItem_bottom">
            <ul>
              <li>
                <span> 应用版本： </span>
                <span>{{ item.version }}</span>
              </li>
                <li>
                <span> 适配容器： </span>
                <span>{{ item.remark || '--' }}</span>
              </li>
              <li>
                <span> 应用大小： </span>
                <span>{{ item.filesize | formatSize }}</span>
              </li>
              <li>
                <span> 厂家： </span>
                <span>{{ item.manufactor }}</span>
              </li>
              <li>
                <span> 操作系统： </span>
                <span>{{ item.operatingSystem }}</span>
              </li>
              <li>
                <span>构架： </span>
                <span>{{ item.framework }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div style="text-align: right">
        <pagination v-show="pagination.total > 0" :pageSizes="[15, 30, 100, 200, 500]" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total"
          @pagination="getPageList" />
      </div>
    </div>
    <el-dialog title="上传应用" :visible.sync="dialogVisible" width="640px" :close-on-click-modal="false" @close="cancle">
      <el-form ref="addForm" :model="addForm" label-width="80px" size="small" :rules="rules">
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="addForm.name" clearable />
        </el-form-item>
        <el-form-item label="应用版本" prop="version">
          <el-input type="input" v-model="addForm.version" clearable />
        </el-form-item>
        <el-form-item label="适配容器" prop="remark">
          <el-select v-model="addForm.remark" style="width: 100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in conList" :value="item.name" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" style="display: none">
          <el-input type="input" v-model="addForm.type" clearable />
        </el-form-item>
        <el-form-item label="生产厂家  " prop="manufactor">
          <el-input type="input" v-model="addForm.manufactor" clearable />
        </el-form-item>
        <el-form-item label="操作系统" prop="operatingSystem">
          <el-input type="input" v-model="addForm.operatingSystem" clearable />
        </el-form-item>
        <el-form-item label="架构" prop="framework">
          <el-input type="input" v-model="addForm.framework" clearable />
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="addForm.tenantId" style="width: 100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件">
          <el-upload class="upload-demo" :multiple="false" :file-list="fileList" ref="upload" :limit="1" accept="*" action="api/v1/file/save" :headers="headers" :data="addForm" :auto-upload="false"
            :on-success="onUploadSuccess" :on-error="onUploadError" :before-upload="beforeUpload" :before-remove="beforeRemove" :on-change="handleChange">
            <el-button size="small" type="primary" @click="uploadList">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div style="text-align: right">
        <el-button type="primary" @click="submitUpload('addForm')" size="small">保存</el-button>
        <el-button @click="cancle" size="small">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="创建应用安装任务" :visible.sync="dialogVisibleAdd" width="640px" :close-on-click-modal="false" @close="cancleTask">
      <el-form ref="addTask" :model="addTask" label-width="80px" size="small" :rules="rulesTask">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="addTask.name" clearable />
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="addTask.tenantId" style="width: 100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <div style="text-align: right">
        <el-button type="primary" @click="addTasks('addTask')" size="small">保存</el-button>
        <el-button @click="cancleTask" size="small">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="" :visible.sync="isLoading" width="200px" :close-on-click-modal="false" :show-close="false" :modal="false" class="lds">
      <loadUpload />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as tenantApi from "@/api/sys/tenant";
import { appPage } from "@/api/application";
import formRule from "@/utils/formRules";
import loadUpload from "@/components/uploadLoading.vue";
import { containerPage } from "@/api/container"

export default {
  data() {
    let account = /^[\u4e00-\u9fa5a-zA-Z-z0-9-_]+$/;
    const validateName = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入应用名称名称"));
      } else {
        if (account.test(value)) {
          callback();
        } else {
          callback(new Error("名称只能出现特殊字符中划线-或下划线_"));
        }
      }
    };
    const validateContainName = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入应用任务名称"));
      } else {
        if (account.test(value)) {
          callback();
        } else {
          callback(new Error("名称只能出现特殊字符中划线-或下划线_"));
        }
      }
    };
    const validateManufactor = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入生产厂家"));
      } else {
        if (account.test(value)) {
          callback();
        } else {
          callback(new Error("名称只能出现特殊字符中划线-或下划线_"));
        }
      }
    };
    return {
      isLoading: false,
      tenantList: [],
      pagination: {
        total: 0,
        page: 1,
        pageSize: 15,
      },
      dialogVisible: false,
      dialogVisibleAdd: false,
      conList:[],
      addForm: {
        name: "",
        version: "",
        type: "",
        manufactor: "",
        operatingSystem: "",
        framework: "",
        tenantId: "",
      },
      files: {},
      addTask: {},
      rules: {
        name: [
          {
            min: 2,
            max: 60,
            message: "长度在 2 到 60 个字符",
            trigger: "blur",
          },
          { required: true, trigger: "blur", validator: validateName },
        ],
        version: formRule.versionNew,
        manufactor: [
          {
            min: 2,
            max: 32,
            message: "长度在 2 到 32 个字符",
            trigger: "blur",
          },
          { required: true, trigger: "blur", validator: validateManufactor },
        ],
        operatingSystem: [
          { required: true, message: "请输入操作系统", trigger: "blur" },
        ],
        framework: [{ required: true, message: "请输入架构", trigger: "blur" }],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
        remark: [
          { required: true, message: "请选择容器", trigger: "change" },
        ],
      },
      rulesTask: {
        name: [
          {
            min: 2,
            max: 32,
            message: "长度在 2 到 32 个字符",
            trigger: "blur",
          },
          { required: true, trigger: "blur", validator: validateContainName },
        ],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
      },
      fileList: [],
      headers: {
        Authorization: getToken(),
      },
      containList: [],
      taskList: [],
    };
  },
  mounted() {
    this.getTenantList();
    this.getPageList();
    this.getConList()
  },
  components: {
    loadUpload,
  },
  methods: {
     getConList() {
      let data = {
        page: 1,
        pageSize: 100,
      }
      containerPage(data).then(res => {
        console.log('res: ', res);
        if (res.code == '200') {
         this.conList = res.data.records
        }
      })
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    getPageList() {
      let data = {
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
      };
      appPage(data).then((res) => {
        if (res.code == "200") {
          this.containList = res.data.records;
          this.pagination.total = res.data.total;
        }
      });
    },
    // deployment() {
    //   this.$router.push({ path: "/applicationDeployment" });
    // },
    addTaskU(val) {
      this.taskList = [val];
      this.dialogVisibleAdd = true;
    },
    submitUpload(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addForm.type = 12;
          if (
            !this.files.status ||
            this.files.status == "fail" ||
            this.files == undefined
          ) {
            return this.$message({
              message: "请上传文件",
              type: "warning",
            });
          } else {
            this.isLoading = true;
            this.$refs.upload.submit();
          }
        } else {
          return false;
        }
      });
    },
    addTasks(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          localStorage.setItem("appName", JSON.stringify(this.addTask));
          localStorage.setItem("taskList", JSON.stringify(this.taskList));
          this.dialogVisibleAdd = false;
          this.$router.push({ path: "/applicationDeployment" });
        }
      });
    },
    cancleTask() {
      this.dialogVisibleAdd = false;
      this.$refs.addTask.resetFields();
    },
    cancle() {
      this.dialogVisible = false;
      this.$refs.addForm.resetFields();
      this.$refs.upload.clearFiles();
      this.files = {};
    },
    beforeRemove(file) {
      this.files = {};
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(f) {
      this.files = f;
    },
    uploadList() { },
    onUploadSuccess(f) {
      if (f.code === 200) {
        this.$message({
          message: f.message,
          type: "success",
        });
        this.isLoading = false;
        this.$refs.upload.clearFiles();
        this.dialogVisible = false;
        this.getPageList();
      } else {
        this.isLoading = false;
        this.files.status = 'ready'
        this.$message({
          message: f.message,
          type: "error",
        });
      }
    },
    onUploadError() {
      //
      this.$message({
        message: "文件上传失败",
        type: "warning",
      });
      this.isLoading = false;
      // this.files = {}
      return;
    },
    beforeUpload(file) {
      // this.files = file
    },
    uploadCon() {
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss">
.applicationShop {
  padding: 20px;
  .containList {
    display: flex;
    align-content: center;
    flex-wrap: wrap;
    // justify-content: space-between;
    margin-top: 20px;
    .containItem {
      min-width: 19%;
      max-width: 19%;
      width: 19%;
      margin-right: 1.25%;
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      padding: 10px 15px;
      margin-bottom: 20px;
      .containItem_top {
        display: flex;
        align-items: center;
        .right {
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex: 1;
          margin-left: 10px;
          > div {
            font-size: 14px;
            margin-right: 10px;
          }
        }
      }
      .containItem_bottom {
        ul {
          li {
            line-height: 20px;
          }
        }
      }
    }
    div.containItem:nth-of-type(5n) {
      margin-right: -1.25%;
    }
  }
}
.lds {
  .el-dialog {
    box-shadow: 0 0 0 rgba(0, 0, 0, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    height: 150px !important;
    margin-top: 30vh !important;
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      height: 150px;
    }
  }
}
</style>
